﻿using System;
using System.ComponentModel;
using GC_FFW.ForecastWriter.Enums;
using GC_FFW.ForecastWriterClient.ViewModels.Parameters;

namespace GC_FFW.ForecastWriterClient.ViewModels
{
	public class ForecastEditorViewModel : INotifyPropertyChanged
	{
		#region Variables

		private readonly ForecastEditorViewModelParameters _parameters;

		private bool _isWindowEnabled;
		private string _forecast;

		#endregion

		#region Properties

		public string Forecast
		{
			get { return _forecast; }
			set
			{
				_forecast = value;
				if (PropertyChanged == null) return;
				PropertyChanged(this, new PropertyChangedEventArgs("Forecast"));
			}
		}

		public bool IsWindowEnabled
		{
			get { return _isWindowEnabled; }
			set
			{
				_isWindowEnabled = value;
				if (PropertyChanged == null) return;
				PropertyChanged(this, new PropertyChangedEventArgs("IsWindowEnabled"));
			}
		}

		#endregion

		#region Constructors

		public ForecastEditorViewModel(ForecastEditorViewModelParameters parameters)
		{
			if (parameters == null)
				throw new ArgumentNullException(string.Format("Parameters"));
			_parameters = parameters;

			if (_parameters.ForecastBuilder == null)
				throw new ArgumentNullException(string.Format("ForecastBuilder"));

			if (_parameters.ForecastData == null)
				throw new ArgumentNullException(string.Format("ForecastData"));

			if (_parameters.ForecastStructureBuilder == null)
				throw new ArgumentNullException(string.Format("ForecastStructureBuilder"));

			FillViewModel();
		}

		#endregion

		#region Internal Implementation

		private void FillViewModel()
		{
			var worker = new BackgroundWorker();
			worker.DoWork += FillViewModel_DoWork;
			worker.RunWorkerCompleted += FillViewModel_DoWorkComplete;
			worker.RunWorkerAsync();
		}

		private void FillViewModel_DoWork(object sender, DoWorkEventArgs e)
		{
			switch (_parameters.MatchType)
			{
				case MatchType.TeamMatch:
					Forecast = _parameters.ForecastBuilder.Generate(_parameters.ForecastData,
						_parameters.ForecastStructureBuilder.GenerateTeamMatchForecastStructure());

					break;
			}
		}

		private void FillViewModel_DoWorkComplete(object sender, RunWorkerCompletedEventArgs e)
		{
			IsWindowEnabled = true;
		}

		#endregion

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void OnPropertyChanged(string propertyName)
		{
			var handler = PropertyChanged;
			if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
		}

		#endregion
	}
}
